function matlab(FNAME,D,varargin)

default = { ...
   'format','%g',@ischar, ...
};
options = passvalopt(default,varargin{:});

try
    D; %#ok<VUNUS>
catch %#ok<CTCH>
   D = [];
end

%**************************************************************************

c = strfun.file2char(FNAME);
command = '\matlab';

allpos = strfind(c,command);
while ~isempty(allpos)
   pos = allpos(1);
   allpos(1) = [];
   open1 = pos(1) + length(command);
   close1 = strfun.matchbrk(c,open1);
   if isempty(close1) || c(close1+1) ~= '{'
      dothrowerror();
   end
   open2 = close1 + 1;
   [close2,expression] = strfun.matchbrk(c,open2);
   if isempty(close2) || c(close2+1) ~= '{'
      dothrowerror();
   end
   open3 = close2 + 1;
   [close3,format] = strfun.matchbrk(c,open3);
   if isempty(D)
      valueString = '';
   else
      if isempty(format)
         formatString = options.format;
      else
         formatString = ['%',format];
      end
      value = dbeval(D,expression);
      valueString = sprintf(formatString,value);
   end
   replace = ['\matlab{',valueString,'}{',expression,'}{',format,'}'];
   c = [c(1:pos-1),replace,c(close3+1:end)];
   oldLength = close3 - pos + 1;
   newLength = length(replace);
   allpos = allpos + newLength - oldLength;
end

char2file(c,FNAME);

% Nested functions.

%**************************************************************************
   function dothrowerror()
      x = c(pos-20:pos+20);
      x = strfun.converteols(x);
      x = strrep(x,char(10),' ');
      utils.error('latex', ...
         'Syntax error in LaTeX \\matlab command: ''...%s...''.',x);      
   end
% dothrowerror().

end